﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.Mvc;
using ElectronicRecords.Models;
using System.Text.RegularExpressions;

namespace ElectronicRecords.Controllers
{
    public class ClientController : Controller
    {
        //
        // GET: /Client/
        private DataManager _dataManager;

        public ClientController(DataManager dataManager)
        {
            _dataManager = dataManager;
        }

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult List()
        {
            ViewData["Title"] = "Справочник клиентов";
            ViewData["Clients"] = _dataManager.Clients.GetClients();
            return View();
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Create()
        {

            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(Clients c)
        {
            string reg = "^[a-z0-9_\\+-]+(\\.[a-z0-9_\\+-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*\\.([a-z]{2,4})$";
            Regex r = new Regex(reg);
            Match match = r.Match(c.Email);
            if (c.Firstname == null || c.Firstname.Length <= 1) ModelState.AddModelError("Firstname",
                "Фамилия должна быть более 1 символа");
            if (c.Lastname == null || c.Lastname.Length <= 1) ModelState.AddModelError("Lastname",
             "Имя должно быть более 1 символа");
            if (c.Phone == null || c.Phone.Length <= 7) ModelState.AddModelError("Phone",
              "Телефон должен быть более 6 символов");
            if (c.Email == null || c.Email.Length <= 6 || !match.Success) ModelState.AddModelError("Email",
               "Email должен быть более 5 символов");

            if (ModelState.IsValid)
            {
                //c.ID_Client = id;
                MembershipUser u = Membership.GetUser(User.Identity.Name);

                c.CreatedBy = (Guid)u.ProviderUserKey;
                _dataManager.Clients.CreateClient(c.Firstname, c.Lastname, c.Phone, c.Email);
               
                return RedirectToAction("List");
            }


            return View();
        }

        public ActionResult Client(int id)
        {
            ViewData.Model = _dataManager.Clients.GetClient(id);
            return View();
        }

        public ActionResult Delete(int id)
        {
            _dataManager.Clients.DeleteClient(id);
            return RedirectToAction("List");
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Edit(int id)
        {
            Clients c=_dataManager.Clients.GetClient(id);
            ViewData.Model = c;

            ViewData["Users"] = new SelectList(_dataManager.Users.GetUsers(), 
                "ProviderUserKey", "UserName", c.CreatedBy);
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(int id, Clients c)
        {
            string reg = "^[a-z0-9_\\+-]+(\\.[a-z0-9_\\+-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*\\.([a-z]{2,4})$";
            Regex r = new Regex(reg);
            Match match = r.Match(c.Email);
            if (c.Firstname==null || c.Firstname.Length <= 1  ) ModelState.AddModelError("Firstname",
                "Фамилия должна быть более 1 символа");
            if (c.Lastname == null || c.Lastname.Length <= 1  ) ModelState.AddModelError("Lastname",
               "Имя должно быть более 1 символа");
            if (c.Phone == null || c.Phone.Length <= 7 ) ModelState.AddModelError("Phone",
               "Телефон должен быть более 6 символов");
            if (c.Email == null || c.Email.Length <= 6 || !match.Success) ModelState.AddModelError("Email",
               "Email должен быть более 5 символов");

            if (ModelState.IsValid)
            {
                c.ID_Client = id;
                MembershipUser u = Membership.GetUser(User.Identity.Name);
               
               // c.CreatedBy = (Guid)u.ProviderUserKey;
                _dataManager.Clients.UpdateClient(c);
                return RedirectToAction("List");
            }
            

            return View();
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Find()
        {

            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Find(string searchStr)
        {
            if (Request.IsAjaxRequest())
            {
                //найдем клиентов
                List<Clients> l = _dataManager.Clients.FindClients(searchStr).ToList<Clients>();
                string result = "";
                result += "<table id=\"maintable\"";
                result += " <tr><th style=\"width:10%\">Действие</th><th style=\"width:10%\">ID</th><th style=\"width:40%\">Фамилия</th><th style=\"width:40%\">Имя</th></tr>";
                foreach (Clients c in l)
                {
                    result += "<tr><td><a href= \"Client/"+c.ID_Client+"><img height=\"24\" width=\"24\" src=\"../../img/sherlock.png\" ></a> <a href= \"Edit/"+c.ID_Client+"><img height=\"24\" width=\"24\"  src=\"../../img/textedit.png\" ></a></td><td>"+c.ID_Client+"</td><td>"+ c.Firstname+"</td><td>"+c.Lastname+"</td></tr>";

                }
                result += "</table>";
                return Content(result);
            }
          

           return View();
   
        }

    }
}
